package main

import (
	"encoding/json"
	"fmt"
	"log"
	"natproxy/pkg/common"
	"net/http"
	"sync"
)

// ConfigAPI 用于管理客户端配置的 API
type ConfigAPI struct {
	mu      sync.Mutex
	running bool
	client  *Client
	config  *Config
	logger  *common.LogManager
}

// NewConfigAPI 创建新的 ConfigAPI 实例
func NewConfigAPI() *ConfigAPI {
	// 创建日志管理器
	logger, err := common.NewLogManager(&common.LogConfig{
		ConsoleLevel: "error",
		FileLogs: []common.FileLog{
			{
				Type:    "config_api",
				Path:    "logs/config_api",
				MaxSize: 10 * 1024 * 1024,
			},
		},
		RetentionDays: 7,
	}, "config_api")

	if err != nil {
		log.Printf("创建配置API日志管理器失败: %v", err)
	}

	return &ConfigAPI{
		running: true,
		logger:  logger,
	}
}

// SetRunning 设置运行状态
func (api *ConfigAPI) SetRunning(running bool) {
	api.mu.Lock()
	defer api.mu.Unlock()
	api.running = running
}

// Start 启动配置 API 服务
func (api *ConfigAPI) Start(port int) error {
	// 状态查询接口
	http.HandleFunc("/status", api.handleStatus)

	// 配置查询接口
	http.HandleFunc("/config", api.handleConfig)

	addr := fmt.Sprintf(":%d", port)
	api.logger.Log(common.LogInfo, "[配置API] 正在启动，监听端口 %d", port)

	return http.ListenAndServe(addr, nil)
}

// Stop 停止配置 API 服务
func (api *ConfigAPI) Stop() {
	api.SetRunning(false)
}

// handleStatus 处理状态请求
func (api *ConfigAPI) handleStatus(w http.ResponseWriter, r *http.Request) {
	api.mu.Lock()
	defer api.mu.Unlock()

	status := map[string]interface{}{
		"running": api.running,
	}

	json.NewEncoder(w).Encode(status)
}

// handleConfig 处理配置请求
func (api *ConfigAPI) handleConfig(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		// 返回当前配置
		json.NewEncoder(w).Encode(api.config)

	case http.MethodPost:
		// 更新配置
		var newConfig Config
		if err := json.NewDecoder(r.Body).Decode(&newConfig); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		api.mu.Lock()
		api.config = &newConfig
		api.mu.Unlock()

		w.WriteHeader(http.StatusOK)

	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}
